package com.xm.xmapp.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;

import com.xm.xmapp.StartActivity;
import com.xm.xmapp.http.ThreadPoolFactory;
import com.xm.xmapp.tools.Helper_SharedPreferences;
import com.xm.xmapp.tools.Tools;

/**
 * UncaughtException澶勭悊绫�,褰撶▼搴忓彂鐢烾ncaught寮傚父鐨勬椂鍊�,鐢辫绫绘潵鎺ョ绋嬪簭,骞惰褰曞彂閫侀敊璇姤鍛�.
 * 
 * @author way
 * 
 */
public class RWCrashHandler implements UncaughtExceptionHandler {
	private UncaughtExceptionHandler mDefaultHandler;// 绯荤粺榛樿鐨刄ncaughtException澶勭悊绫�
	private static RWCrashHandler INSTANCE = new RWCrashHandler();// CrashHandler瀹炰緥
	private Context mContext;// 绋嬪簭鐨凜ontext瀵硅薄
	private Map<String, String> info = new HashMap<String, String>();// 鐢ㄦ潵瀛樺偍璁惧淇℃伅鍜屽紓甯镐俊鎭�
	private SimpleDateFormat format = new SimpleDateFormat(
			"yyyy-MM-dd HH-mm-ss");// 鐢ㄤ簬鏍煎紡鍖栨棩鏈�,浣滀负鏃ュ織鏂囦欢鍚嶇殑涓�閮ㄥ垎

	/** 淇濊瘉鍙湁涓�涓狢rashHandler瀹炰緥 */
	private RWCrashHandler() {

	}

	/** 鑾峰彇CrashHandler瀹炰緥 ,鍗曚緥妯″紡 */
	public static RWCrashHandler getInstance() {
		return INSTANCE;
	}

	/**
	 * 鍒濆鍖�
	 * 
	 * @param context
	 */
	public void init(Context context) {
		mContext = context;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 鑾峰彇绯荤粺榛樿鐨刄ncaughtException澶勭悊鍣�
		Thread.setDefaultUncaughtExceptionHandler(this);// 璁剧疆璇rashHandler涓虹▼搴忕殑榛樿澶勭悊鍣�
	}

	/**
	 * 褰揢ncaughtException鍙戠敓鏃朵細杞叆璇ラ噸鍐欑殑鏂规硶鏉ュ鐞�
	 */
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			// 濡傛灉鑷畾涔夌殑娌℃湁澶勭悊鍒欒绯荤粺榛樿鐨勫紓甯稿鐞嗗櫒鏉ュ鐞�
			mDefaultHandler.uncaughtException(thread, ex);
		} else {

			// int len = AppCommon.activityList.size();
			// for (int i = 0; i < len; i++) {
			// if(AppCommon.activityList.get(i) != null){
			// AppCommon.activityList.get(i).finish();
			// }
			// }
			try {
				Thread.sleep(3000);// 濡傛灉澶勭悊浜嗭紝璁╃▼搴忕户缁繍琛�3绉掑啀閫�鍑猴紝淇濊瘉鏂囦欢淇濆瓨骞朵笂浼犲埌鏈嶅姟鍣�
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				android.os.Process.killProcess(android.os.Process.myPid());
				System.exit(0);
			}
		}
	}

	/**
	 * 鑷畾涔夐敊璇鐞�,鏀堕泦閿欒淇℃伅 鍙戦�侀敊璇姤鍛婄瓑鎿嶄綔鍧囧湪姝ゅ畬鎴�.
	 * 
	 * @param ex
	 *            寮傚父淇℃伅
	 * @return true 濡傛灉澶勭悊浜嗚寮傚父淇℃伅;鍚﹀垯杩斿洖false.
	 */
	public boolean handleException(Throwable ex) {
		if (ex == null)
			return false;

	

		// 鏀堕泦璁惧鍙傛暟淇℃伅
		collectDeviceInfo(mContext);
		// 淇濆瓨鏃ュ織鏂囦欢
		
		final String result = saveCrashInfo2File(ex);
	
		
		
		
		ThreadPoolFactory.getInstance().execute(new Runnable() {

			@Override
			public void run() {
				// 
				Looper.prepare();
				
				Tools.showMessage("寰堟姳姝�,绯荤粺鍙戠敓閿欒,鍗冲皢閫�鍑猴紝璇烽噸鏂扮櫥褰�");
				Intent intent = new Intent(MyAppcation.getMyAppcation(),
						StartActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
//				intent.putExtra("result", result);
//				Log.d("ldw", "result==>"+result);
				MyAppcation.getMyAppcation().startActivity(intent);

				Looper.loop();
			}
		});
	
		
		return true;
	}

	/**
	 * 鏀堕泦璁惧鍙傛暟淇℃伅
	 * 
	 * @param context
	 */
	public void collectDeviceInfo(Context context) {
		try {
			PackageManager pm = context.getPackageManager();// 鑾峰緱鍖呯鐞嗗櫒
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_ACTIVITIES);// 寰楀埌璇ュ簲鐢ㄧ殑淇℃伅锛屽嵆涓籄ctivity
			if (pi != null) {
				String versionName = pi.versionName == null ? "null"
						: pi.versionName;
				String versionCode = pi.versionCode + "";
				info.put("versionName", versionName);
				info.put("versionCode", versionCode);
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		Field[] fields = Build.class.getDeclaredFields();// 鍙嶅皠鏈哄埗
		for (Field field : fields) {
			try {
				field.setAccessible(true);
				info.put(field.getName(), field.get("").toString());
				
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	private String saveCrashInfo2File(Throwable ex) {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : info.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key + "=" + value + "\r\n");
		}
		Writer writer = new StringWriter();
		PrintWriter pw = new PrintWriter(writer);
		ex.printStackTrace(pw);
		Throwable cause = ex.getCause();
		// 寰幆鐫�鎶婃墍鏈夌殑寮傚父淇℃伅鍐欏叆writer涓�
		while (cause != null) {
			cause.printStackTrace(pw);
			cause = cause.getCause();
		}
		pw.close();// 璁板緱鍏抽棴
		String result = writer.toString();
		
		sb.append(result);
		// 淇濆瓨鏂囦欢
		// long timetamp = System.currentTimeMillis();
		String time = format.format(new Date());
		String fileName = time + "_YY.log";
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -30);
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				File dir = new File(CodeConstant.RootFileL);
				if (!dir.exists())
					dir.mkdir();

				FileOutputStream fos = new FileOutputStream(dir + "/"
						+ fileName);
				fos.write(sb.toString().getBytes());
				
				Helper_SharedPreferences.set_str_sp("error", sb.toString());
			
				// 鍙戦�佺粰寮�鍙戜汉鍛�
				// sendCrashLog2PM(dir + fileName);
				fos.close();
				return fileName;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	/**
	 * 灏嗘崟鑾风殑瀵艰嚧宕╂簝鐨勯敊璇俊鎭彂閫佺粰寮�鍙戜汉鍛� 鐩墠鍙皢log鏃ュ織淇濆瓨鍦╯dcard 鍜岃緭鍑哄埌LogCat涓紝骞舵湭鍙戦�佺粰鍚庡彴銆�
	 */
	// private void sendCrashLog2PM(String fileName) {
	// if (!new File(fileName).exists()) {
	// Toast.makeText(mContext, "鏃ュ織鏂囦欢涓嶅瓨鍦紒", Toast.LENGTH_SHORT).show();
	// return;
	// }
	// postFile(fileName,AppCommonData.ERRORLOG);
	// }
	// public void postFile(final String fileName,final String requestURL){
	// File file = new File(fileName);
	// if(file.exists() && file.length()>0){
	// AsyncHttpClient client = new AsyncHttpClient();
	// RequestParams params = new RequestParams();
	// try {
	// params.put("logfile", file);
	// client.post(requestURL, params,new AsyncHttpResponseHandler() {
	// @Override
	// public void onSuccess(int arg0, String arg1) {
	// Log.e("sss", "鎴愬姛");
	// }
	// @Override
	// public void onFailure(Throwable arg0, String arg1) {
	// try {
	// Thread.sleep(5000);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// postFile(fileName,requestURL);
	// }
	// @Override
	// public void onFinish() {
	// super.onFinish();
	// // Toast.makeText(MainActivity.this, "鎴愬姛...........",
	// Toast.LENGTH_LONG).show();
	// }
	// });
	// } catch (FileNotFoundException e) {
	// e.printStackTrace();
	// }
	// }
	// }
}
